{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Widgets Events\n",
    "\n",
    "A deeper dive into working with the callbacks and events when widget values change."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import ipywidgets as widgets\n",
    "from IPython.display import display\n",
    "from traitlets import HasTraits"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Traitlets events"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every widget inherits from [traitlets.HasTraits](https://traitlets.readthedocs.io/en/stable/api.html#traitlets.HasTraits), which provides the functionality of observing values, linking wiht other widgets, and for validation of values. You can learn more about traitlets in it's [user guide](https://traitlets.readthedocs.io/en/stable/using_traitlets.html#using-traitlets)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every `HasTraits` class has an `observe` method which allows observing properties changes. You can assign a Python callback function that will be called when a property changes.\n",
    "\n",
    "The callback handler passed to observe will be called with one change argument. The change object holds at least a `type` key and a `name` key, corresponding respectively to the type of notification and the name of the attribute that triggered the notification.\n",
    "\n",
    "Other keys may be passed depending on the value of `type`. In the case where type is `change`, we also have the following keys:\n",
    "\n",
    "- `owner` : the HasTraits instance\n",
    "- `old` : the old value of the modified trait attribute\n",
    "- `new` : the new value of the modified trait attribute\n",
    "- `name` : the name of the modified trait attribute."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Registering callbacks to trait changes in the kernel\n",
    "\n",
    "Since `Widget` classes inherit from `HasTraits`, you can register handlers to the change events whenever the model gets updates from the front-end or from other code.\n",
    "\n",
    "\n",
    "To investigate this lets take the final example from the previous section with the small change of removing the `names=True`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Create and display our widgets\n",
    "slider = widgets.FloatSlider(description='Input:')\n",
    "square_display = widgets.HTML(description=\"Square: \", value='{}'.format(slider.value**2))\n",
    "display(widgets.VBox([slider, square_display]))\n",
    "\n",
    "# Create function to update square_display's value when slider changes\n",
    "def update_square_display(change):\n",
    "    square_display.value = '{}'.format(change.new**2)\n",
    "    \n",
    "\n",
    "slider.observe(update_square_display) # removed names=\"value\"\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Importance of `names` argument\n",
    "\n",
    "That didn't work! And where did our error messages go?\n",
    "\n",
    "\n",
    "### Seeing error messages in callbacks\n",
    "\n",
    "1. Jupyterlab Log console\n",
    "2. `widgets.Output()`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Create and display our widgets\n",
    "slider = widgets.FloatSlider(description='Input:')\n",
    "square_display = widgets.HTML(description=\"Square: \", value='{}'.format(slider.value**2))\n",
    "display(widgets.VBox([slider, square_display]))\n",
    "\n",
    "\n",
    "# We use an output widget here for capturing the print calls and showing them at the right place in the Notebook\n",
    "output = widgets.Output()\n",
    "display(output)\n",
    "\n",
    "# Create function to update square_display's value when slider changes\n",
    "@output.capture()\n",
    "def update_square_display(change):\n",
    "    print(change)\n",
    "    square_display.value = '{}'.format(change.new**2)\n",
    "    \n",
    "slider.observe(update_square_display) # removed names=\"value\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After investigating, we can see that we are getting notifications for the `_property_lock` trait. This is why it's important to use the\n",
    "`names=` argument."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Create and display our widgets\n",
    "slider = widgets.FloatSlider(description='Input:')\n",
    "square_display = widgets.HTML(description=\"Square: \", value='{}'.format(slider.value**2))\n",
    "display(widgets.VBox([slider, square_display]))\n",
    "output = widgets.Output()\n",
    "display(output)\n",
    "@output.capture()\n",
    "def update_square_display(change):\n",
    "    print(change)\n",
    "    square_display.value = '{}'.format(change.new**2)\n",
    "\n",
    "    \n",
    "slider.observe(update_square_display, names=\"value\") # added back the names=\"value\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This captures all changes to the value, not just those made using the mouse."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "slider.value = .3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### What are the valid arguments to `names`?\n",
    "Any named trait that the widget has can be observed. You can see what traits a widget has with the `.traits()` method"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "slider.traits()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `.value` and validation\n",
    "\n",
    "Most of the `ipywidgets` widgets have a `.value` trait that corresponds to the data type they represent. In addition to powering `observe` traitlets also performs validation and coercion for these values. So if you try to set one to the wrong type you will get an error or it may be coerced to a new data type."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "int_slider = widgets.IntSlider()\n",
    "float_slider = widgets.FloatSlider()\n",
    "\n",
    "# fine\n",
    "float_slider.value = 5.5\n",
    "\n",
    "# Will get rounded to an int\n",
    "int_slider.value = 5.5\n",
    "print(int_slider.value)\n",
    "\n",
    "# raises an error\n",
    "int_slider.value = \"5.5\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise\n",
    "\n",
    "\n",
    "Using `observe` and the `Output` widget print out the reverse of the text string in the `Textarea` widget below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "text = widgets.Textarea()\n",
    "output = widgets.Output()\n",
    "\n",
    "# ...\n",
    "# ...\n",
    "\n",
    "display(text, output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# %load solutions/observe-reverse.py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Should you use `observe` or `link`?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When to use observe\n",
    "\n",
    "`observe` is most useful when you want to have a sideeffect on something that is not a widget (e.g. modifying a matplotlib plot, or saving a file), or when you need to information on the previous value. \n",
    "\n",
    "`link` is the easiest way to connect traits of two widgets together. You can also transform the values by passing a function to the `transform` argument.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "slider1 = widgets.IntSlider()\n",
    "slider2 = widgets.IntSlider()\n",
    "widgets.link((slider1, \"value\"), (slider2, \"value\"))\n",
    "\n",
    "display(slider1, slider2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You aren't limited in linking `value` with `value`. Any traits that have compatible types can be linked. In this example the `min` value of the main slider is controlled by the second slider."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "main_slider = widgets.IntSlider(value=3, min=0, max=10, description=\"main slider\")\n",
    "min_slider = widgets.IntSlider(value=0, min = -10, max=10, description=\"min slider\")\n",
    "widgets.link((main_slider, \"min\"), (min_slider, \"value\"))\n",
    "display(widgets.VBox([main_slider, min_slider]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "Using `widgets.link` with the `transform` argument and the two functions to make both text boxes update when the other is modified."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def C_to_F(temp):\n",
    "    return 1.8 * temp + 32\n",
    "\n",
    "def F_to_C(temp):\n",
    "    return (temp -32) / 1.8\n",
    "\n",
    "degree_C = widgets.FloatText(description='Temp $^\\circ$C', value=0)\n",
    "degree_F = widgets.FloatText(description='Temp $^\\circ$F', value=C_to_F(degree_C.value))\n",
    "\n",
    "display(degree_C, degree_F)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# %load solutions/temperature-link.py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Advanced Widget Linking"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Earlier you used `link` to link the value of one widget to another. \n",
    "\n",
    "There are a couple of other linking methods that offer more flexibility:\n",
    "\n",
    "+ `dlink` is a *directional* link; updates happen in one direction but not the other.\n",
    "+ `jslink` and `jsdlink` do the linking in the front end\n",
    "    - While the linking happens in the frontend the Python objects still have their values updated."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### dlink in the kernel (ie. in Python)\n",
    "\n",
    "The first method is to use the `link` and `dlink`. This only works if we are interacting with a live kernel."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "caption = widgets.HTML(value='Changes in source values are reflected in target1, but changes in target1 do not affect source')\n",
    "source, target1 = widgets.IntSlider(description='Source'),\\\n",
    "                  widgets.IntSlider(description='Target 1')\n",
    "\n",
    "display(caption, source, target1)\n",
    "\n",
    "dl = widgets.dlink((source, 'value'), (target1, 'value'))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Links can be broken by calling `unlink`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "dl.unlink()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Linking widgets attributes from the client side"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also directly link widget attributes in the browser using the link widgets, in either a unidirectional or a bidirectional fashion.\n",
    "\n",
    "Javascript links persist when embedding widgets in html web pages without a kernel."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "caption = widgets.Label(value='The values of range1 and range2 are synchronized')\n",
    "range1, range2 = widgets.IntSlider(description='Range 1'),\\\n",
    "                 widgets.IntSlider(description='Range 2')\n",
    "\n",
    "display(caption, range1, range2)\n",
    "\n",
    "l = widgets.jslink((range1, 'value'), (range2, 'value'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "caption = widgets.Label(value='Changes in source_range values are reflected in target_range1')\n",
    "source_range, target_range1 = widgets.IntSlider(description='Source range'),\\\n",
    "                              widgets.IntSlider(description='Target range 1')\n",
    "\n",
    "display(caption, source_range, target_range1)\n",
    "\n",
    "dl = widgets.jsdlink((source_range, 'value'), (target_range1, 'value'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The links can be broken by calling the `unlink` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "l.unlink()\n",
    "dl.unlink()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The difference between `link` and `jslink`\n",
    "\n",
    "**Python Linking**\n",
    "\n",
    "Pros:\n",
    "1. Allows transformation of values\n",
    "\n",
    "Cons:\n",
    "1. Worse performance\n",
    "2. Does not persist when kernel is not running.\n",
    "\n",
    "**Client Linking**\n",
    "\n",
    "Pros:\n",
    "1. Works without a kernel\n",
    "2. Faster GUI updates\n",
    "\n",
    "Cons:\n",
    "1. No transformations\n",
    "\n",
    "For more details on the difference see the [documentation](https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html#The-difference-between-linking-in-the-kernel-and-linking-in-the-client)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "leader = widgets.IntSlider(description=\"leader\")\n",
    "py_follower = widgets.IntSlider(description='python link')\n",
    "js_follower = widgets.IntSlider(description='client link')\n",
    "\n",
    "display(leader, js_follower, py_follower)\n",
    "\n",
    "l_js = widgets.jslink((leader, 'value'), (js_follower, 'value'))\n",
    "l_py = widgets.link((leader, 'value'), (py_follower, 'value'))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Continuous vs delayed updates\n",
    "\n",
    "Some widgets offer a choice with their `continuous_update` attribute between continually updating values or only updating values when a user submits the value (for example, by pressing Enter or navigating away from the control). In the next example, we see the \"Delayed\" controls only transmit their value after the user finishes dragging the slider or submitting the textbox. The \"Continuous\" controls continually transmit their values as they are changed. Try typing a two-digit number into each of the text boxes, or dragging each of the sliders, to see the difference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "a = widgets.IntSlider(description=\"Delayed\", continuous_update=False)\n",
    "b = widgets.IntText(description=\"Delayed\", continuous_update=False)\n",
    "c = widgets.IntSlider(description=\"Continuous\", continuous_update=True)\n",
    "d = widgets.IntText(description=\"Continuous\", continuous_update=True)\n",
    "\n",
    "widgets.jslink((a, 'value'), (b, 'value'))\n",
    "widgets.jslink((a, 'value'), (c, 'value'))\n",
    "widgets.jslink((a, 'value'), (d, 'value'))\n",
    "widgets.VBox([a,b,c,d])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Widgets defaulting to  `continuous_update=True`:\n",
    "\n",
    "- Sliders\n",
    "- `Text`\n",
    "- `Textarea`\n",
    "\n",
    "Widgets defaulting to `continuous_updateFalse`:\n",
    "\n",
    "- Textboxes for entering numbers (e.g. `IntText`)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Special events"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some widgets like the `Button` have special events on which you can hook Python callbacks."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `Button` is not used to represent a data type.  Instead the button widget is used to handle mouse clicks.  The `on_click` method of the `Button` can be used to register function to be called when the button is clicked.  The doc string of the `on_click` can be seen below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "widgets.Button.on_click?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Example"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since button clicks are stateless, they are transmitted from the front-end to the back-end using custom messages.  By using the `on_click` method, a button that prints a message when it has been clicked is shown below. To capture `print`s (or any other kind of output including errors) and ensure it is displayed, be sure to send it to an `Output` widget (or put the information you want to display into an `HTML` widget)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "button = widgets.Button(description=\"Click Me!\")\n",
    "output = widgets.Output()\n",
    "\n",
    "display(button, output)\n",
    "\n",
    "@output.capture()\n",
    "def on_button_clicked(b):\n",
    "    print(\"Button clicked.\")\n",
    "\n",
    "button.on_click(on_button_clicked)"
   ]
  }
 ],
 "metadata": {
  "cell_tags": [
   [
    "<None>",
    null
   ]
  ],
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
